<?php
/**
 * @file $HeadURL: imageperson.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2014-12-30 下午7:41:55 $
 * @brief 
 */
namespace haibao\cms\data;


class ImagePerson extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ImagePerson');
	}
	
	/**
	 * 添加新的图片与标签的关联关系
	 * @param int $imageId
	 * @param array $persons
	 */
	public function addImagePersons($imageIds, $persons){
		if(!$persons){
			return false;
		}
		$this->beginTranscation();
		try {
			$imageIds = (array)$imageIds;
			$persons = (array)$persons;
			$str = preg_replace('/(\d+)/', '%s', implode(',', $persons));
				
			// 删除旧的关联关系
			$this->deleteImagePersons($imageIds);
				
			//添加新的关联关系
			$sql = 'insert into ImagePerson(ImageId, Name) values ';
			$arrSql = $arrValues = array();
				
			foreach($imageIds as $imageId){
				foreach ($persons as $person){
					array_push($arrSql, '(%s,%s)');
					array_push($arrValues, $imageId);
					array_push($arrValues, $person);
				}
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 删除旧的图片和人物的关联关系
	 * @param array $imageIds
	 */
	public function deleteImagePersons($imageIds){
		if(!$imageIds){
			return false;
		}
		$imageIds = (array)$imageIds;
		$imageIdStr = implode(',', $imageIds);
		$str = preg_replace('/(\d+)/', '%s', $imageIdStr);
	
		$sql = "delete from ImagePerson where ImageId in ({$str})";
		$this->query($sql, $imageIds);
	}
	
	/**
	 * 根据主键查询所有人物名称
	 */
	public function getPersonsById($id){
		$id = (array)$id;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $id));
		
		$data = array();
		$result = $this->query("select * from `ImagePerson` where `id` in ($str)", $id);
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\cms\model\data\ImagePerson();
			$model->loadArray($row);
			array_push($data, $model);
		}
		return $data;
	}
}